package ophiux.alipay.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;



public class HttpUtil {
	private static ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
	public static String HTTP_POST = "POST";
	public static String HTTP_GET = "GET";
	
	public static String token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";

	public static String getAccessToken(String appId, String appSecret) {
		String requestUrl = token_url.replace("APPID", appId).replace("APPSECRET", appSecret);
		String resToken = HttpUtil.sendPost(requestUrl, null);
		resToken=resToken.substring(17,resToken.indexOf(",")-1);
		return resToken;
	}
	
	/**
	 * 
	 * @param requestUrl  
	 * @param requestMethod  
	 * @param outputStr  
	 * @return
	 * @throws Exception
	 */
	public static String httpsRequest(String requestUrl,String requestMethod,
			String outputStr) throws Exception{
		return httpsRequest(requestUrl, requestMethod, outputStr, 30*1000);
	}
	
	/**
	 * 
	@param requestUrl  请求地址
	 * @param requestMethod 	请求方式
	 * @param outputStr  
	 * @param timeout   超时时间
	 * @return
	 * @throws Exception
	 */
	public static String httpsRequest(String requestUrl,String requestMethod,
							String outputStr,int timeout) throws Exception{
		
		StringBuffer buffer = null;
		try {
			URL url = new URL(requestUrl);
			
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(requestMethod);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setConnectTimeout(timeout);
			conn.connect();
			if(outputStr != null){
				OutputStream os = conn.getOutputStream();
				os.write(outputStr.getBytes("utf-8"));
				os.close();
			}
			
			InputStream is = conn.getInputStream();
			InputStreamReader isr = new InputStreamReader(is,"gbk");
			BufferedReader br = new BufferedReader(isr);
			
		    buffer = new StringBuffer(); 
			String line = null;
			
			while((line = br.readLine())!=null){
				buffer.append(line);
			}
			
		} catch (Exception e) {
			throw e;
		}
		return buffer.toString();
		
		
		
       /* URL httpUrl = new URL(requestUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        httpURLConnection.setRequestProperty("Host", "api.mch.weixin.qq.com");
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod(requestMethod);
        httpURLConnection.setConnectTimeout(10*1000);
        httpURLConnection.setReadTimeout(10*1000);
        httpURLConnection.connect();
        OutputStream outputStream = httpURLConnection.getOutputStream();
        outputStream.write(outputStr.getBytes("UTF-8"));

        //获取内容
        InputStream inputStream = httpURLConnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        final StringBuffer stringBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            stringBuffer.append(line);
        }
        String resp = stringBuffer.toString();
        if (stringBuffer!=null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream!=null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream!=null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
		return resp;*/
	}
	

	
	public static String post(final String url, final String param) {
	    Callable callable = new Callable<String>() {
	        public String call() throws Exception {
	          return HttpUtil.sendPost(url, param);
	        }
	      };
	    Future<String> temp = fixedThreadPool.submit(callable);
	    try {
	      return temp.get();
	    }
	    catch(Exception e) {
	    	e.printStackTrace();
	    }
	    return null;
	  }
	
	
	public static String sendPost(String url, String param) {
	    PrintWriter out = null;
	    BufferedReader in = null;
	    String result = "";
	    try {
	      URL realUrl = new URL(url);
	      // 打开和URL之间的连接
	      URLConnection conn = realUrl.openConnection();
	      // 设置通用的请求属性
	      conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
	      // 发送POST请求必须设置如下两行
	      conn.setDoOutput(true);
	      conn.setDoInput(true);
	      // 获取URLConnection对象对应的输出流
	      OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
	      out = new PrintWriter(outWriter);
	      // 发送请求参数
	      out.print(param);
	      // flush输出流的缓冲
	      out.flush();
	      // 定义BufferedReader输入流来读取URL的响应
	      in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	      String line;
	      while((line = in.readLine()) != null) {
	        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
	        result += line;
	      }
	    }
	    catch(Exception e) {
	      System.out.println("发送 POST 请求出现异常！" + e);
	      e.printStackTrace();
	    }
	    // 使用finally块来关闭输出流、输入流
	    finally {
	      try {
	        if(out != null) {
	          out.close();
	        }
	        if(in != null) {
	          in.close();
	        }
	      }
	      catch(IOException ex) {
	        ex.printStackTrace();
	      }
	    }
	    return result;
	  }
}
